<?php
declare(strict_types=1);
namespace app\admin\controller;

use app\common\AdminController;
use app\admin\model\Role as RoleDB;
use app\utils\Redis as RedisDB;
class RedisInit extends AdminController
{
    protected $roleDB;
    protected $uRedis;
    protected $pRedis;
    public function initialize()
    {
        $this->roleDB = new RoleDB();
        $this->uRedis = new RedisDB('user');
        $this->pRedis = new RedisDB('perms');
    }

    public function initPerms()
    {
        try {
            $perms = [];
            $res = $this->roleDB->select();
            $res->each(function ($item) use (&$perms) {
                $perms['perms:roleId:' . $item['id']] = $item->menu->column('perms');
            });
            $perms['perms:roleId:' . $this->adminRoleId] = ['*:*:*'];
            $this->pRedis->multi();
            foreach ($perms as $key => $item) {
                if (count($item) > 0) {
                    $this->pRedis->sAdd($key, $item);
                }
            }
            $resutl = $this->pRedis->exec();
            return success("初始化成功", $resutl);
        } catch (\Throwable $th) {
            $this->pRedis->discard();
            return error("初始化失败", $th->getMessage());
        }
    }


}